import React, {useRef, useEffect} from 'react';
import echarts from 'echarts';
export default function barMap(props) {
  const barNode = useRef(null);
  let myecharts = null;
  useEffect(() => {
    getBar();
    window.addEventListener('resize', () => {
      myecharts && myecharts.resize();
    });
  },[props.data]);
  useEffect(() => {
    return () => {
      myecharts && myecharts.dispose();
      window.removeEventListener('resize', ()=> {myecharts && myecharts.resize();})
    }
  },[])
  const centers = (props.center && {center: props.center}) || {};
  const colors = props.colorOptions || [
    '#c23531',
    '#2f4554',
    '#61a0a8',
    '#d48265',
    '#91c7ae',
    '#749f83',
    '#ca8622',
    '#bda29a',
    '#6e7074',
    '#546570',
    '#c4ccd3',
  ];
  const labelOption = Object.assign({
    show: false, // 是否显示文字
    position: 'normal', // 定位
    fontSize: '16',
    formatter: '{b}  {c} {d}%',
  }, props.labelOption);
  const legend = props.isLegend ? {legend: Object.assign({
    orient: 'horizontal',
    x: 'center',
    y: 'bottom',
    icon: 'circle',
    data: props.data.map(it => it.name)
  }, props.legendOptions)} : {};
  function getBar() {
    const option = {
        title: [{
            text: props.title || '',
            top: 10,
            left: 10
        }],
        // color: colors,
        tooltip: {
            trigger: 'item',
            formatter: '{b}: {c} ({d}%)'
        },
        ...legend,
        series: [
          {
            type: 'pie',
            radius: props.radius || ['40%', '60%'],
            ...centers,
            avoidLabelOverlap: false,
            label: {
              ...labelOption
            },
            emphasis: {
                label: {
                    show: false,
                    // fontSize: '16', // 字体大小
                    fontWeight: 'bold'
                }
            },
            labelLine: {
                show: labelOption.show
            },
            itemStyle: {
              normal: {
                borderColor: '#fff',
                borderWidth: 2,
                color: (params) => {
                  return params.data.color || colors[params.dataIndex]
                }
              }
            },
            data: props.data
          }
        ]
    };
    const renderedInstance = echarts.getInstanceByDom(barNode.current);
    if (renderedInstance) {
      myecharts = renderedInstance;
    } else {
      myecharts = echarts.init(barNode.current);
    }
    myecharts.setOption(option, true);
  }
  return (
    <div ref={barNode}></div>
  )
}